package com.example.weixinpayment.task;

import com.example.weixinpayment.entity.OrderInfo;
import com.example.weixinpayment.entity.RefundInfo;
import com.example.weixinpayment.service.OrderInfoService;
import com.example.weixinpayment.service.RefundInfoService;
import com.example.weixinpayment.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: weixin-payment
 * @description: 定时任务
 * @author: LiuZhuzheng
 * @create: 2022-01-11 19:05
 **/
@Slf4j
@Component
public class WxPayTask {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 秒 分 时 日 月 周
     *
     * 日和周不能同时指定，指定其中一个另一个设为？
     * * 指所有
     * ？ 不指定
     * 1-3 1到3
     * 1/3 从1开始 间隔3
     * 1，2，3 所有的1，2，3执行
     *
     *
     * 每隔30秒查询一次 创建超过5分钟未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void orderConfirm() throws Exception {
        List<OrderInfo> orderInfoList = orderInfoService.getNoPayOrderByDuration(5);

        for (OrderInfo orderInfo : orderInfoList) {
            String orderNo = orderInfo.getOrderNo();
            log.warn("timeout order , the orderNo is {}", orderNo);

            // 调用微信端接口核实订单状态
            wxPayService.checkOrderStatus(orderNo);
        }
    }

    /**
     * 从第0秒开始每隔30秒执行1次，查询创建超过5分钟，并且未成功的退款单
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void refundConfirm() throws Exception {
        log.info("refundConfirm 被执行......");

        //找出申请退款超过5分钟并且未成功的退款单
        List<RefundInfo> refundInfoList = refundInfoService.getNoRefundOrderByDuration(5);

        for (RefundInfo refundInfo : refundInfoList) {
            String refundNo = refundInfo.getRefundNo();
            log.warn("超时未退款的退款单号 ===> {}", refundNo);

            //核实订单状态：调用微信支付查询退款接口
            wxPayService.checkRefundStatus(refundNo);
        }
    }
}
